import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Observable } from 'rxjs'
import { AuthGuard } from '@nestjs/passport'
import { ConfigService } from '@nestjs/config'
import { Reflector } from '@nestjs/core'

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(
    private readonly config: ConfigService,
    private reflector: Reflector,
  ) {
    super()
  }
  canActivate(
    ctx: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const req = ctx.switchToHttp().getRequest()
    const noAuth = this.reflector.get<boolean>('no-auth', ctx.getHandler())
    if (
      this.config.get('whiteList').some(item => {
        return req.url.includes(item)
      }) ||
      noAuth
    ) {
      return true
    } else {
      return super.canActivate(ctx)
    }
  }
}
